'use strict';

const Controller = require('egg').Controller;
const jwt=require('jsonwebtoken')

class LoginController extends Controller {
    //登录
    async login() {
        const { ctx } = this;
        const { username, password } = ctx.request.body;
        const post = await this.app.mysql.get('userlist', { username, password });
        if (post) {
            ctx.body = {
                code: 200,
                msg: '登录成功',
                nickname: post.nickname,
                token:jwt.sign({nickname:post.nickname},'1906A')
            }
        } else {
            ctx.body = {
                code: 401,
                msg: '登录失败'
            }
        }
    }
    //注册
    async register() {
        const { ctx } = this;
        const { username, password, nickname } = ctx.request.body;
        const post = await this.app.mysql.get('userlist', { username });
        if (!post) {
            let sql = `INSERT INTO userlist (username,password,nickname,id) VALUES ('${username}', '${password}', '${nickname}', NULL);`
            const data = await this.app.mysql.query(sql)
            if (data.affectedRows === 1) {
                ctx.body = {
                    code: 200,
                    msg:'注册成功'
                }
            } else {
                ctx.body = {
                    code: 400,
                    msg:'注册失败'
                }
            }
        } else {
            ctx.body = {
                code: 302,
                msg: '此账号已被注册'
            }
        }
    }
}

module.exports = LoginController;
